import { createStore } from 'vuex';

export default createStore({
    state: {
        token: sessionStorage.getItem('token') || null, // 从 sessionStorage 恢复 token
        adminInfo: JSON.parse(sessionStorage.getItem('adminInfo')) || { username: '', role: '' }, // 从 sessionStorage 恢复 adminInfo
    },
    mutations: {
        setToken(state, token) {
            state.token = token;
            sessionStorage.setItem('token', token); // 将 token 保存到 sessionStorage
        },
        setAdminInfo(state, adminInfo) {
            state.adminInfo = adminInfo;
            sessionStorage.setItem('adminInfo', JSON.stringify(adminInfo)); // 将 adminInfo 保存到 sessionStorage
        },
    },
    getters: {
        getAdminInfo(state) {
            return state.adminInfo;
        },
        getToken(state) {
            return state.token;
        },
    },
    actions: {
        // 登录时更新 store 状态
        login({ commit }, { token, adminInfo }) {
            commit('setToken', token);
            commit('setAdminInfo', adminInfo);
        },
        // 退出登录时清空状态
        logout({ commit }) {
            commit('setToken', null);
            commit('setAdminInfo', { username: '', role: '' });
            sessionStorage.removeItem('token'); // 清除 sessionStorage 中的 token
            sessionStorage.removeItem('adminInfo'); // 清除 sessionStorage 中的 adminInfo
        },
    },
});

